package com.zeji.androidadvance.activity.touchFollow;

import android.content.Context;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.Nullable;
import com.zeji.androidadvance.utils.CommonUtil;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.disposables.Disposable;

import java.util.concurrent.TimeUnit;

public class AutoDropView extends View {
    private static final int STEP_LENGTH = 15;
    View targetView;

    RectF myLocation = new RectF();
    RectF targetLocation = new RectF();

    Disposable moveDisposable;
    IEventListener eventListener;

    public AutoDropView(Context context) {
        super(context);
    }

    public AutoDropView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public void setTargetView(View view) {
        targetView = view;
    }

    public void setEventListener(IEventListener eventListener) {
        this.eventListener = eventListener;
    }

    public void start(double speed) {
        if (moveDisposable != null && !moveDisposable.isDisposed()) {
            return;
        }
        final int stepLength = (int) (STEP_LENGTH * speed);
        moveDisposable = Observable.interval(25, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(aLong -> layout(getLeft(), getTop() + stepLength, getRight(), getBottom() + stepLength));
    }

    public void end() {
        CommonUtil.dispose(moveDisposable);
        layout(getLeft(), - getHeight(), getRight(), 0);
    }

    @Override
    public void layout(int l, int t, int r, int b) {
        super.layout(l, t, r, b);
        myLocation.set(l, t, r, b);
        targetLocation.set(targetView.getLeft(), targetView.getTop(), targetView.getRight(), targetView.getBottom());
        if (targetLocation.intersect(myLocation)) {
            eventListener.onAttachTarget();
            end();
        } else if (b >= ((View) getParent()).getHeight()) {
            eventListener.onFailed();
            end();
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        CommonUtil.dispose(moveDisposable);
        targetView = null;
    }

    public interface IEventListener {
        void onAttachTarget();

        void onFailed();
    }
}
